﻿using System;
using System.Globalization;
using EpiNEXT.Services;

namespace EpiNEXT.Services.Validation.Functions
{
    public sealed class Years : DateDiffBase
    {
        public Years()
            : base()
        {
        }

        public override object Evaluate(Record record, params object[] parameters)
        {
            object boxedParamDateStart = parameters[0];
            object boxedParamDateEnd = parameters[1];

            // one or both values are null; cannot evaluate (e.g. x + 5 = what? can't eval without knowing x)
            if (boxedParamDateStart == null || boxedParamDateEnd == null)
            {
                return null;
            }

            if (String.IsNullOrEmpty(boxedParamDateStart.ToString().Trim()) || String.IsNullOrEmpty(boxedParamDateEnd.ToString().Trim()))
            {
                return null;
            }

            SetDates(boxedParamDateStart, boxedParamDateEnd, record);

            if (StartDate.HasValue == false || EndDate.HasValue == false)
            {
                return null;
            }

            DateTime zeroTime = new DateTime(1, 1, 1);
            TimeSpan span = EndDate.Value - StartDate.Value;
            // because we start at year 1 for the Gregorian 
            // calendar, we must subtract a year here.
            int years = (zeroTime + span).Year - 1;

            return years;
        }

        public override object Execute(Record record)
        {
            object result = base.Execute(record);

            if (result == null)
            {
                return result;
            }
            else if(result is TimeSpan)
            {
                TimeSpan span = (TimeSpan)result;

                if (span.Days < 0)
                {
                    return null;
                }

                DateTime zeroTime = new DateTime(1, 1, 1);

                // because we start at year 1 for the Gregorian 
                // calendar, we must subtract a year here.
                int years = (zeroTime + span).Year - 1;

                return years;
            }
            else
            {
                return null;
            }
        }
    }
}
